import fs from 'fs'
import typescript from '@rollup/plugin-typescript'
import dts from 'rollup-plugin-dts'
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import { babel } from '@rollup/plugin-babel'
import replace from '@rollup/plugin-replace'
import terser from '@rollup/plugin-terser'
import { string } from 'rollup-plugin-string'

export default () => {
	let version = '1.0.0'
	try {
		const data = fs.readFileSync('./package.json', 'utf8')
		const json = JSON.parse(data)
		version = json.version
	} catch (err) {
		console.error('读取版本信息失败: ', err)
	}

	const plugins = [
		replace({
			'process.env.VERSION': JSON.stringify(version),
			preventAssignment: true
		}),
		typescript({
			tsconfig: './tsconfig.json'
		}),
		resolve({
			browser: true, // 如果需要浏览器环境
			preferBuiltins: false // 如果打包 Node.js 模块
		}),
		commonjs(),
		json(),
		babel({
			babelHelpers: 'bundled',
			extensions: ['.ts', '.tsx'],
			presets: ['@babel/preset-env']
		}),
		string({
			include: 'src/html/*.html'
		})
	]

	const input = 'src/ts/index.ts'

	return [
		{
			input,
			output: [
				{
					file: './dist/index.esm.js',
					format: 'es',
					sourcemap: false
				}
			],
			plugins
		},
		{
			input,
			output: [
				{
					file: './dist/index.min.js',
					format: 'umd',
					name: 'MicroPlayer',
					sourcemap: false
				}
			],
			plugins: [terser(), ...plugins]
		},
		{
			input,
			output: [{ file: 'dist/index.d.ts', format: 'es' }],
			plugins: [dts()]
		}
	]
}
